package com.faner4cloud.yun.common.xss.core;

import com.faner4cloud.yun.common.util.SpringContextHolder;
import com.faner4cloud.yun.common.xss.config.XssProperties;
import com.faner4cloud.yun.common.xss.util.XssUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author ...zz
 * @version v1
 * @summary desc
 * @since 2022/5/4 3:16 PM
 */
@Slf4j
public class XssCleanDeserializer extends JsonDeserializer<String> {

	@Override
	public String deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
		// XSS filter
		String text = p.getValueAsString();
		if (text == null) {
			return null;
		}
		// 读取 xss 配置
		XssProperties properties = SpringContextHolder.getBean(XssProperties.class);
		if (properties == null) {
			return text;
		}
		// 读取 XssCleaner bean
		XssCleaner xssCleaner = SpringContextHolder.getBean(XssCleaner.class);
		if (xssCleaner == null) {
			return XssUtil.trim(text, properties.isTrimText());
		}
		String value = xssCleaner.clean(XssUtil.trim(text, properties.isTrimText()));
		log.debug("Json property value:{} cleaned up by xss, current value is:{}.", text, value);
		return value;
	}

}
